package com.example.controller;

import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;

public class UpFile {

    public static void upload2() throws ClientProtocolException, IOException {

        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        System.out.println("111==================");
        CloseableHttpResponse httpResponse = null;

        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(200000).setSocketTimeout(200000000).build();

        HttpPost httpPost = new HttpPost("http://hs.api.chenglai.net/api/PhyscialMachine/UpLoad");

        httpPost.setConfig(requestConfig);

        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();

        File file = new File("c:\\1.png");


        System.out.println("=222=================");
        multipartEntityBuilder.addBinaryBody("file",file);

        multipartEntityBuilder.addTextBody("comment", "this is comment");

        HttpEntity httpEntity = multipartEntityBuilder.build();

        httpPost.setEntity(httpEntity);

        httpResponse = httpClient.execute(httpPost);

        HttpEntity responseEntity = httpResponse.getEntity();

        int statusCode= httpResponse.getStatusLine().getStatusCode();
        System.out.println("333==================");
        System.out.println( httpResponse);
        System.out.println("statusCode==================" + statusCode);
        if(statusCode == 200){
            BufferedReader reader = new BufferedReader(new InputStreamReader(responseEntity.getContent()));
            StringBuffer buffer = new StringBuffer();
            String str = "";
            while(!StringUtil.isEmpty(str = reader.readLine())) {
                buffer.append(str);
            }
            System.out.println("==================");
            System.out.println(buffer.toString());
        }
        httpClient.close();

        System.out.println("=4444=================");
        if(httpResponse!=null){
            httpResponse.close();
        }

    }
}
